// pages/my/my.js
const app = getApp()
var server = require('../../../utils/server');
var util = require('../../../utils/util.js');
var that
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tu: app.globalData.tupian,
    denglu: 1,
    userID: '',
    PageIndex: 1,
    dj: 1,
    img: app.globalData.tupian + '13.png',
    userInfo: {},
    user: {},
    zq: '0',
    xh1: '4',
    zp: [],
    xh: [],
    xhlength: 0,
    hasNext: true,
    startTime: 0,   //点击开始时间
    endTime: 0,　 //点击结束时间
    shancu: 1,
    endindex: 0,
    touch: false,//是否触摸还是点击
    Slide: false,//是否滑动
    redirect: 0
  },

  onLoad: function (e) {
    that = this
    if (e.redirect === 1) {
      this.setData({
        redirect: 1
      });
    }
  },
  onShow: function (e) {
    that = this
    const res = wx.getStorageSync('token')
    const userID = wx.getStorageSync('_id')
    const openid = wx.getStorageSync('openid')
    const userInfo = wx.getStorageSync('userInfo')
    const result = wx.getStorageSync('result')
    app.globalData.result = result
    that.setData({
      userInfo: userInfo,
      zp: [],
      xh: [],
    })
    if (res) {
      console.log('111')
      app.globalData.token = res
      app.globalData.userID = userID
      app.globalData.openid = openid
      app.globalData.userInfo = userInfo
      that.xihuan(1, userID)
  
      server.requestForm(false, 'get', 'user', {
        filter: {
          _id: userID,
        }
      },
        function (e) {
          if (e.code == 0) {
            var d = new Date(e.data[0].birthday.replace(/-/g, '/'));
            var times = d.getFullYear();
            e.data[0].birthday = util.formatyear(new Date()) - times;
            console.log(e, times, util.formatyear(new Date()))
            that.setData({
              user: e.data[0]
            })
            if (!e.data[0].backgroundPicPath) {
              let user = that.data.user
              let key = "backgroundPicPath";
              let value = app.globalData.tupian + '13.png'
              that.data.user[key] = value
              that.setData({
                user: user
              })
            }
            if (!e.data[0].birthday) {
              let user = that.data.user
              let key = "birthday";
              let value = 0
              that.data.user[key] = value
              that.setData({
                user: user
              })
            }
            if (!e.data[0].city) {
              let user = that.data.user
              let key = "city";
              let value = '中国'
              that.data.user[key] = value
              that.setData({
                user: user
              })
            }
            if (!e.data[0].context) {
              let user = that.data.user
              let key = "context";
              let value = '还没填写个性签名'
              that.data.user[key] = value
              that.setData({
                user: user
              })
            }
            if (!e.data[0].careID) {
              let user = that.data.user
              let key = "careID";
              let value = []
              that.data.user[key] = value
              that.setData({
                user: user
              })
            }
            if (!e.data[0].fansID) {
              let user = that.data.user
              let key = "fansID";
              let value = []
              that.data.user[key] = value
              that.setData({
                user: user
              })
            }
          } else {
            wx.showToast({
              title: e.message,
              icon: 'none',
              duration: 1000,
            });
          }

        })
      that.setData({
        denglu: 2,
        userID: userID,
        userInfo: userInfo,
        PageIndex: 1
      })
    } else {
      console.log('222',that.data)
      var user = {
        backgroundPicPath: app.globalData.tupian + '13.png'
      }
      that.setData({
       // denglu: 1,
        user: user
      })
    }
  },
  zuopin: function (PageIndex, userID) {
    var zp = that.data.zp
    server.requestForm(false, 'get', 'card', {
      page: ({
        size: 4,
        index: PageIndex
      }),
      filter: {
        authorID: userID
      },
      sort: {
        createTime: -1
      }
    }, function (e) {
      console.log(e)
      for (var i in e.data.items) {
        e.data.items[i].shancu = 1
        zp.push(e.data.items[i])
      }
      console.log('zp', zp)
      that.setData({
        zp: zp,
        zq: e.data.count,
        hasNext: e.data.hasNext
      })
    })
  },
  xihuan: function (PageIndex, userID) {
    var xh = that.data.xh
    server.requestForm(true, 'get', 'card/getLike', {
      page: ({
        size: 4,
        index: PageIndex
      }),
      filter: {
        userID: userID
      }
    }, function (e) {
      console.log(e)
      if (e.code == 0) {
        for (var i in e.data.items) {
          xh.push(e.data.items[i])
        }
        console.log('xh', xh)
        that.zuopin(1, userID)
        that.setData({
          xh: xh,
          xhlength: e.data.count,
          hasNext: e.data.hasNext
        })
      } else {
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 1000,
        });
      }

    })
  },
  dj: function (e) {
    that.setData({
      xh: [],
      zp: [],
    })
    var dj = e.currentTarget.dataset.dd
    if (dj == 1) {
      that.zuopin(1, that.data.userID)
    } else {
      that.xihuan(1, that.data.userID)
    }
    that.setData({
      dj: dj,
      PageIndex: 1,
    })
  },

  //删除卡片
  deletecard: function (e) {
    var id = e.currentTarget.dataset.id
    console.log('11111')
    wx.showModal({
      title: '是否删除卡片',
      // content: '模态弹窗',
      success: function (res) {
        if (res.confirm) {
          server.requestForm(false, 'delete', 'card/' + id, {
            // id: id,
          }, function (e) {
            console.log('删除', e)
            if (e.code == 0) {
              var list = that.data.zp
              list.splice(that.data.endindex, 1)
              that.setData({
                zp: list,
                zq: that.data.zq - 1
              })
              // that.onShow()
            } else {
              wx.showToast({
                title: e.message,
                icon: 'none',
                duration: 1000,
              });
            }
            // that.onShow()
          })
        } else {
          console.log('用户点击取消')
        }
      }
    })


  },


  //长按点击区分
  touchStart: function (e) {
    console.log('触摸开始', e)
    for (var i in that.data.zp) {
      that.data.zp[i].shancu = 1
    }
    that.setData({
      // startTime : e.timeStamp,
      zp: that.data.zp,
      endindex: e.currentTarget.dataset.index,
      Slide: false,
      touch: false
    })
  },
  touchEnd: function (e) {
    console.log('触摸结束', e)
    var id = e.currentTarget.dataset.id
    console.log(that.data.touch, '123', that.data.Slide)
    if (!that.data.touch && that.data.Slide) {
      console.log('11')
    } else {
      console.log('22')
      that.carddetails(id)

    }
  },

  //长按事件
  bingLongTap: function (e) {
    console.log('长按')
    that.setData({
      touch: true
    })
    
    //这里可以做长按事件要处理的
    that.data.zp[that.data.endindex].shancu = 2
    console.log('changan')
    that.setData({
      zp: that.data.zp
    })
  },

  onPageScroll: function (e) {
    console.log('滑动')
    that.fanh()
    that.setData({
      Slide: true
    })
  },



  fanh: function (e) {
    for (var i in that.data.zp) {
      that.data.zp[i].shancu = 1
    }
    that.setData({
      zp: that.data.zp
    })
  },

  carddetails: function (e) {
    console.log('id', e)
    // var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../../carddetails/carddetails?id=' + e,
    })
  },
  carddetails1:function(e){
  var id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../../carddetails/carddetails?id=' + id,
    })
  },
  mydetails: function (e) {
    wx.navigateTo({
      url: '../../mydetails/mydetails',
    })
  },
  fans: function (e) {
    console.log(e)
    var dj = e.currentTarget.dataset.gz
    wx.navigateTo({
      url: '../../fans/fans?dj=' + dj + '&fanscount=' + that.data.user.fansID.length + '&carecount=' + that.data.user.careID.length,
    })
  },
  sy: function (e) {
    wx.reLaunch({
      url: '../../index/index',
    })
  },
  fx: function (e) {
    wx.reLaunch({
      url: '../../find/find',
    })
  },
  xx: function (e) {
    wx.reLaunch({
      url: '../../news/news',
    })
  },
  sys: function (e) {
    wx.reLaunch({
      url: '../../laboratory/laboratory',
    })
  },


  //获取手机号
  getPhoneNumber(e) {
    console.log('获取手机号', e)
    console.log(e.detail.errMsg)
    console.log(e.detail.iv)
    console.log(e.detail.encryptedData)
    const result = wx.getStorageSync('result')
    const userInfo = wx.getStorageSync('userInfo')
    server.requestForm(false, 'post', 'user/wxdecrypt', {
      sessionKey: result.session_key,
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
    }, function (wxdecrypt) {
      console.log('wxdecrypt', wxdecrypt)
      if(wxdecrypt.code==0){
        app.globalData.userInfo = userInfo
        server.requestForm(false, 'put', 'user', {
          _id: result._id,
          headPicPath: userInfo.avatarUrl,
          nickname: userInfo.nickName,
          commentState: 1,
          tel:wxdecrypt.data.phoneNumber
          // sex: sex
        }, function (e) {
          console.log(e)
          wx.setStorageSync('token',result.token)
          wx.setStorageSync('_id', result._id)
          that.sy()
        })

      }else{
        that.setData({
          denglu:1
        })
      }
     
    })
   
  },

//授权登录
  onGotUserInfo: function (e) {
    console.log(e)
    if (e.detail.errMsg == 'getUserInfo:ok') {
      wx.login({
        success: function (res) {
          console.log('111', res)
          wx.showToast({
            title: '加载中',
            mask: true,
            icon: 'loading'
          })
          server.requestForm(false, 'post', 'user/wxlogin', {
            code: res.code
          }, function (e) {
            console.log(e)
            wx.getUserInfo({
              success: function (res) {
                console.log('dddddd', res)
                var userInfo = res.userInfo
                wx.setStorageSync('userInfo', userInfo);
               
                that.setData({
                  denglu:3
                })
              }
            })
            wx.setStorageSync('openid', e.data.openid)
            wx.setStorageSync('result', e.data)
          })
        }
      })
    } else {

    }
  },
  onReachBottom: function (e) {
    console.log('that.data.hasNext', that.data.hasNext)
    if (that.data.hasNext) {
      that.setData({
        PageIndex: that.data.PageIndex + 1
      })
      console.log(that.data)
      if (that.data.dj == 1) {
        that.zuopin(that.data.PageIndex, that.data.userID)
      } else {
        that.xihuan(that.data.PageIndex, that.data.userID)
      }
    }
  },
  toApply(){
    wx.navigateTo({
      url: '../apply/apply',
    })
  },
  toCoupon(){
    wx.navigateTo({
      url: '../coupon/coupon',
    })
  },
  toComplain(){
    wx.navigateTo({
      url: '../complain/complain',
    })
  },
  toOrder(e){
    wx.setStorageSync('myorder-page-type', e.currentTarget.dataset.type);
    wx.switchTab({
      url: '/pages/dish/myorder/myorder?type=' + e.currentTarget.dataset.type,
    })
  }
})